package com.zxinlee.account.tcc.impl;

import com.zxinlee.account.entity.Account;
import com.zxinlee.account.mapper.AccountMapper;
import com.zxinlee.account.tcc.AccountTccAction;
import com.zxinlee.account.tcc.ResultHolder;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Component
public class AccountTccActionImpl implements AccountTccAction {

    @Autowired
    private AccountMapper accountMapper;

    @Transactional
    @Override
    public boolean prepare(BusinessActionContext businessActionContext, Long userId, BigDecimal money) {

        //先查询判断可以金额是否足够
        Account account = accountMapper.findByUserId(userId, money);
        if (account.getResidue().compareTo(money) < 0)
            throw new RuntimeException("可用金额不足");
        accountMapper.updateResidueToFrozen(userId, money);

        //一阶段成功,添加幂等性
        ResultHolder.setResult(AccountTccAction.class, businessActionContext.getXid(), "p");

        return true;
    }

    @Transactional
    @Override
    public boolean commit(BusinessActionContext businessActionContext) {

        if (ResultHolder.getResult(AccountTccAction.class, businessActionContext.getXid()) == null)
            return true;

        Long userId = Long.valueOf(businessActionContext.getActionContext("userId").toString());
        BigDecimal money = new BigDecimal(businessActionContext.getActionContext("money").toString());
        accountMapper.updateFrozenToUsed(userId,money);

        ResultHolder.removeResult(AccountTccAction.class,businessActionContext.getXid());
        return true;
    }

    @Transactional
    @Override
    public boolean rollback(BusinessActionContext businessActionContext) {

        if (ResultHolder.getResult(AccountTccAction.class,businessActionContext.getXid())==null)
            return true;

        Long userId = Long.valueOf(businessActionContext.getActionContext("userId").toString());
        BigDecimal money = new BigDecimal(businessActionContext.getActionContext("money").toString());
        accountMapper.updateFrozenToResidue(userId,money);

        ResultHolder.removeResult(AccountTccAction.class,businessActionContext.getXid());
        return true;
    }
}
